package ch02.classPath.Entry;

import java.io.*;

/**
 * 为 Entry 的实现类
 * 通过绝对路径读取 .class 文件
 */
public class DirEntry extends Entry{
    String absPath;

    public DirEntry(String path) throws ClassNotFoundException {
        File file = new File(path);
        if(!file.exists()){
            throw new ClassNotFoundException();
        }else {
            this.absPath = file.getAbsolutePath();
        }

    }

    @Override
    public byte[] readClass(String className) throws IOException {
        File classFile = new File(this.absPath, className);
        if(!classFile.exists()){
            return null;
        }
        byte[] buffer = new byte[1024];
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(classFile));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        int size = 0;

        while((size = in.read(buffer)) != -1){
            out.write(buffer,0, size);
        }

        if(in != null){
            in.close();
        }

        if(out != null){
            out.close();
        }

        return out.toByteArray();
    }

    @Override
    public String string() {
        return absPath;
    }

    public static void main(String[] args) {
        try {
            DirEntry dirEntry = new DirEntry("F:\\mine-jvm\\out\\production\\mine-jvm\\ch01");
            byte[] bytes = dirEntry.readClass("Cmd.class");
            System.out.println(bytes.length);

            System.out.println(dirEntry.string());
        } catch (ClassNotFoundException | IOException e) {
            System.out.println("error");
            e.printStackTrace();
        }
    }
}
